<?php

namespace App\Http\Middleware;

use Closure;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Http\Request;
use App\Http\Lib\ResBase;
use App\Http\Lib\TokenServise;
use function PHPUnit\Framework\isEmpty;

class isLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, Closure $next)
    {
            // 从请求头中获取token
            $token = $request->header('access-token');
//            var_dump($token);
            if(!isset($token)) {
                return response()->json(['code'=>500,'data'=>'未登录','msg'=>'failed']);
//                return ResBase::ApiRes(500,'未登录','failed');
            } else {
                // 进行解密和验证
                $key = 'base64:hpwfh8pGl6R81+/y1ZcZ91HgM2p4/7H5vRlqhb2QhDw='; // 替换为你的秘钥
                try {
                    $decoded = JWT::decode($token,new Key($key,'HS256'));
                    //var_dump($decoded->uid);
                    // 如果验证通过，可以继续执行下一个中间件或请求处理器
                    return $next($request);
                }  catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
//                    return ResBase::ApiRes(501,'身份已过期','failed');
                    return response()->json(['code'=>501,'data'=>'身份已过期','msg'=>'failed']);
                } catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
//                    return ResBase::ApiRes(501,'身份已过期','failed');
                    return response()->json(['code'=>501,'data'=>'身份已过期','msg'=>'failed']);
                }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
//                    return ResBase::ApiRes(501,'身份已过期','failed');
                    return response()->json(['code'=>501,'data'=>'身份已过期','msg'=>'failed']);
                } catch (\Exception $e) {
                    // 如果验证失败，返回错误响应
//                    return ResBase::ApiRes(501,'身份已过期','failed');
                    return response()->json(['code'=>501,'data'=>'身份已过期','msg'=>'failed']);
                }

            }
    }
}
